import React, { useEffect, useRef, useState} from "react";
import * as echarts from 'echarts';
import './index.scss';
import {UserOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space, Typography, message } from 'antd';
import { useNavigate } from "react-router";
import instance from "../../utlis";
const Index:React.FC=()=>{
  const userInfo = JSON.parse(localStorage.getItem('userInfo')! ||'') 
  const [allArticles,setAllArticles] = useState([])
  console.log(allArticles)
  // console.log(userInfo)
  const navigate = useNavigate()
  const items: MenuProps['items'] = [
  {
    key: '1',
    label: '个人中心',
  },
  {
    key: '2',
    label: '用户管理',
  },
  {
    key: '3',
    label: '系统设置',
  },
  {
    key: '4',
    label: '退出登录',
  }
];

const handleMenuClick=(key:string)=>{
  if(key === '4'){
       localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
      navigate('/login')
  }
  if(key === '2' && userInfo.role === '管理员'){
    navigate('/user')
     return  message.success('欢迎管理员')
  } 
  return message.error('访客无权')
}
const getallArticles=async()=>{
    try {
       const config = {
        url:'/api/get_allArticles',
        method:'get'
    }
    const res = await instance(config)
    // console.log(res)
    const {data} = res
    setAllArticles(data.data)
      
    } catch (error) {
      console.log(error)
      
    }
}
useEffect(()=>{
  getallArticles()
},[])
     const categories = (function () {
      let now = new Date();
      let res = [];
      let len = 10;
      while (len--) {
        res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''));
        now = new Date(+now - 2000);
      }
      return res;
    })();
    const categories2 = (function () {
      let res = [];
      let len = 10;
      while (len--) {
        res.push(10 - len - 1);
      }
      return res;
    })();
    const data: number[] = (function () {
      let res = [];
      let len = 10;
      while (len--) {
        res.push(Math.round(Math.random() * 1000));
      }
      return res;
    })();
    const data2: number[] = (function () {
      let res = [];
      let len = 0;
      while (len < 10) {
        res.push(+(Math.random() * 10 + 5).toFixed(1));
        len++;
      }
      return res;
    })();
   
     const chartRef = useRef<HTMLDivElement>(null);
     useEffect(() => {
      if (chartRef.current) {
        const myChart = echarts.init(chartRef.current);
        const option = {
        title: {
          text: 'Dynamic Data'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#283b56'
            }
          }
        },
        legend: {},
        toolbox: {
          show: true,
          feature: {
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {}
          }
        },
        dataZoom: {
          show: false,
          start: 0,
          end: 100
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: true,
            data: categories
          },
          {
            type: 'category',
            boundaryGap: true,
            data: categories2
          }
        ],
        yAxis: [
          {
            type: 'value',
            scale: true,
            name: 'Price',
            max: 30,
            min: 0,
            boundaryGap: [0.2, 0.2]
          },
          {
            type: 'value',
            scale: true,
            name: 'Order',
            max: 1200,
            min: 0,
            boundaryGap: [0.2, 0.2]
          }
        ],
        series: [
          {
            name: 'Dynamic Bar',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data
          },
          {
            name: 'Dynamic Line',
            type: 'line',
            data: data2
          }
        ]
      };
        myChart.setOption(option);
        // 返回一个清除函数，用于在组件卸载时销毁 echarts 实例
        return () => {
          myChart.dispose();
        };
      }
    }, []);
    const handerArticles=()=>{
       navigate('/article/allarticle')
    }
    const handercomment=()=>{
      navigate('/comment')
    }
    return(
        <div className="container">
          <div className="content-top">
             <div className="left">
                 <p>工作台</p>
                  <h1>您好:{userInfo.username}</h1>
                  <p>您的角色:{userInfo.role}</p>
             </div>
             <div className="right">
              <img src={userInfo.img} alt=""  style={{width:'30px'}}/>
                 <div>
                    <Dropdown
                  menu={{
                    items,
                    selectable: true,
                    // defaultSelectedKeys: ['3'] 
                    onClick:({key})=>handleMenuClick(key)
                  }}
                >
                  <Typography.Link>
                    <Space>
                      <UserOutlined  style={{fontSize:'30px'}}/>
                    </Space>
                  </Typography.Link>
                </Dropdown>
                 </div>
                <div>Hi,{userInfo.username}</div>
             </div>
          </div>
           <div className="content">
            <div ref={chartRef} style={{ width: '100%', height: '400px' }} className="eacharts"></div>
              <div className="subany">
                <h2>快速导航</h2>
                <ul>
                  <li onClick={()=>handerArticles()}>文章管理</li>
                  <li onClick={()=>handercomment()}>评论管理</li>
                  <li>文件管理</li>
                  <li>用户管理</li>
                  <li>访问管理</li>
                  <li>系统设置</li>
                </ul>
              </div>
              <div className="updateArticles">
                <h2>最新文章</h2>
                  <div className="updateArticles-item">
                    {
                      allArticles.map((v)=>{
                        return(
                           <div></div>
                        )
                      })
                    }
                     </div>
                </div>
           </div>
        </div>
    )
}
export default Index